class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) 
    {
        sort(nums.begin(),nums.end());
        vector<vector<int>> ans;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]>=0&&nums[i]>target)
            {
                return ans;
            }
            if(i>0&&nums[i]==nums[i-1])
            {
                continue;
            }
            for(int j=i+1;j<nums.size();j++)
            {         
                if(nums[j]>=0&&nums[j]+nums[i]>target)
                {
                  //不能直接return，nums[i]+nums[j]不行，但是nums[i+1]和nums[i+2]有可能
                    break;
                }
                if(j>i+1&&nums[j]==nums[j-1])
                {
                    continue;
                }
            
                int sum=nums[i]+nums[j];
                int left=j+1;
                int right=nums.size()-1;
                while(left<right)
                {
                    if((long)nums[left]+nums[right]>(long)target-sum)
                    {
                        right--;
                    }
                    else if((long)nums[left]+nums[right]<(long)target-sum)
                    {
                        left++;
                    }
                    else
                    {
                        ans.push_back(vector<int>{nums[i],nums[j],nums[left],
                        nums[right]});
                        while(left<right&&nums[left]==nums[left+1])
                        {
                            left++;
                        }
                        while(left<right&&nums[right]==nums[right-1])
                        {
                            right--;
                        }
                        left++;
                        right--;
                    }
                }
            }
        }
        return ans;
    }
};
